package cn.wildfire.chat.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.sourcemuch.im.caiba.BuildConfig;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.BaseActivity;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.classes.RegionRet;
import cn.wildfire.chat.app.extendsion.classes.ResponseJsonResultEntity;
import cn.wildfire.chat.app.extendsion.classes.SendCodeRequest;
import cn.wildfire.chat.app.extendsion.classes.UserCheckRequest;
import cn.wildfire.chat.app.extendsion.classes.ViewTimerSet;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfirechat.remote.ChatManager;


/**
 * Create by HEKE, 2019/8/13 12:02
 * TODO 注册界面
 */
public class RegisterActivity extends BaseActivity {

    @BindView(R2.id.countrySelector)
    TextView countrySelector;
    @BindView(R2.id.phoneNymber)
    EditText phoneNymber;
    @BindView(R2.id.password)
    EditText password;
    @BindView(R2.id.registerBut)
    Button registerBut;
    @BindView(R2.id.authCodeEditText)
    EditText authCodeEditText;
    @BindView(R2.id.requestAuthCodeButton)
    TextView requestAuthCodeButton;
    @BindView(R2.id.repeatPassword)
    EditText repeatPassword;
    @BindView(R2.id.selectedCountryTxt)
    TextView selectedCountryTxt;
    @BindView(R2.id.loginTxt)
    TextView loginTxt;
    @BindView(R2.id.iv_auth_code)
    ImageView ivAuthCode;
    @BindView(R2.id.rl_img_auth_code)
    RelativeLayout rlImgAuthCode;
    @BindView(R2.id.et_invite_code)
    EditText etInviteCode;
    @BindView(R2.id.iv_password_hide_or_show)
    ImageView ivPasswordHideOrShow;
    @BindView(R2.id.iv_password_check_hide_or_show)
    ImageView ivPasswordCheckHideOrShow;

    /**
     * 区号设置
     */
    private RegionRet mRegionRet;
    private Region currentRegion; // 当前所在国家区号对象

    /**
     * 渠道ID
     */
    private String channelImId;

    private String cid;
    private String codeType;

    @Override
    public void initViews() {
        bindBack();
        setLevel(2);
        hideToolbar();
        channelImId = BuildConfig.REGISTER_ID;
        try {
            cid = ChatManager.Instance().getClientId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        getCodeType();

        currentRegion = getIntent().getParcelableExtra("Region");
        if (currentRegion == null) {
            currentRegion = new Region(438, "86", getString(R.string.default_country));
        }
        selectedCountryTxt.setText(currentRegion.regionName);
        postRegionDatas();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
    }

    @OnClick({R2.id.countrySelector, R2.id.registerBut, R2.id.iv_auth_code})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.countrySelector) {
            Intent intent = new Intent(RegisterActivity.this, CountrySetActivity.class);
            intent.putExtra("RegionList", mRegionRet);
            startActivityForResult(intent, 101);
        } else if (id == R.id.registerBut) {
            String phoneNumber = phoneNymber.getText().toString().trim();
            if (!usercheckLock && !TextUtils.isTextEmpty(phoneNumber)) {
                usercheckLock = true;
                new UserCheckRequest(this, phoneNumber, new UserCheckRequest.OnUserCheckResultListener() {
                    @Override
                    public void result(boolean existed) {
                        usercheckLock = false;
                        register();
                    }
                });
            }
        } else if (id == R.id.iv_auth_code) {
            if (cid != null) {
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE);
                Glide.with(RegisterActivity.this).load(ServerUrlClient.GET_RANDOM_VIFCODE + "?cid=" + cid)
                        .apply(requestOptions).into(ivAuthCode);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调选择国家编码
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            currentRegion = data.getParcelableExtra("mRegion");
            if (currentRegion != null) {
                selectedCountryTxt.setText(currentRegion.regionName);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 注册
    private void register() {
        try {
            String phoneNumber = phoneNymber.getText().toString().trim();
            String password2 = password.getText().toString().trim();
            String repeatPassword2 = repeatPassword.getText().toString().trim();
            String phonecode = authCodeEditText.getText().toString().trim();
            String invitedCode = "";
            invitedCode = etInviteCode.getText().toString().trim();
            if (TextUtils.isTextEmpty(phoneNumber) || TextUtils.isTextEmpty(password2) || TextUtils.isTextEmpty(phonecode) || TextUtils.isTextEmpty(repeatPassword2)) {
                Toast.makeText(this, "请输入完整信息!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!password2.equals(repeatPassword2)) {
                Toast.makeText(this, "两次输入密码不一致!", Toast.LENGTH_SHORT).show();
                repeatPassword.setText("");
                return;
            }
            if (!TextUtils.isTextEmpty(invitedCode) && invitedCode.length() != 6) {
                Toast.makeText(this, "邀请码为6位数", Toast.LENGTH_SHORT).show();
                return;
            }

            //点击下一步,跳转至设置密保问题
            Intent intentSetSecurityQuestion = new Intent(RegisterActivity.this, SetSecurityQuestionActivity.class);

            HashMap<String, String> params = new HashMap<>();
            params.put("code", phonecode);
            params.put("mobile", phoneNumber);
            params.put("password", password2);
            params.put("regionId", "" + currentRegion.id);
            params.put("cid", ChatManager.Instance().getClientId());
            params.put("codetype", codeType);
            params.put("inviteCode", invitedCode);
            //params.put("trenchCode", "" + channelImId);
            intentSetSecurityQuestion.putExtra("registerMessage", (Serializable) params);
            intentSetSecurityQuestion.putExtra("region", currentRegion);
            startActivity(intentSetSecurityQuestion);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCodeType() {
        OkHttpRequest.getNewInstance(this).requestAsynJsonObject(ServerUrlClient.GET_CODE_TYPE, null, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                try {
                    String ret = result.toString();
                    if (ret != null) {
                        Gson gson = new Gson();
                        ResponseJsonResultEntity responseJsonResultEntity = gson.fromJson(result.toString(), ResponseJsonResultEntity.class);
                        codeType = String.valueOf(responseJsonResultEntity.getResult());
                        if (responseJsonResultEntity.getResult().equals("0")) {
                            requestAuthCodeButton.setVisibility(View.GONE);
                            rlImgAuthCode.setVisibility(View.VISIBLE);
                            if (cid != null) {
                                RequestOptions requestOptions = new RequestOptions();
                                requestOptions.skipMemoryCache(true)
                                        .diskCacheStrategy(DiskCacheStrategy.NONE);
                                Glide.with(RegisterActivity.this).load(ServerUrlClient.GET_RANDOM_VIFCODE + "?cid=" + cid)
                                        .apply(requestOptions).into(ivAuthCode);
                            }
                        } else {
                            requestAuthCodeButton.setVisibility(View.VISIBLE);
                            rlImgAuthCode.setVisibility(View.GONE);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        }).request();
    }


    protected boolean usercheckLock;
    protected ViewTimerSet viewTimerSet;

    @OnClick(R2.id.requestAuthCodeButton)
    public void authCodeClicked() {
        try {
            String phoneNumber = phoneNymber.getText().toString();
            if (TextUtils.isTextEmpty(phoneNumber)) {
                Toast.makeText(this, "请输入手机号!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!usercheckLock) {
                if (viewTimerSet != null && !viewTimerSet.isTimeoutFinished()) {
                    return;
                }
                usercheckLock = true;
                new UserCheckRequest(this, phoneNumber, new UserCheckRequest.OnUserCheckResultListener() {
                    @Override
                    public void result(boolean existed) {
                        usercheckLock = false;
                        if (existed) {
                            Toast.makeText(RegisterActivity.this, "用户已存在!", Toast.LENGTH_SHORT).show();
                        } else {
                            viewTimerSet = new ViewTimerSet(RegisterActivity.this, requestAuthCodeButton);
                            viewTimerSet.run();
                            new SendCodeRequest(RegisterActivity.this, phoneNumber, "" + currentRegion.id, new SendCodeRequest.OnSendCodeListener() {
                                @Override
                                public void send(boolean success) {
                                    if (!success) {
                                        viewTimerSet.forceInterrupt();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取区号数据
     */
    private void postRegionDatas() {
        OkHttpRequest.getNewInstance(this).requestAsyn(ServerUrlClient.REGION, OkHttpRequest.TYPE_POST_JSON, null, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                try {
                    String ret = result.toString();
                    if (ret != null) {
                        RegionRet regionRet = new Gson().fromJson(ret, RegionRet.class);
                        if (regionRet != null) {
                            regionRet.regionArrayList = new ArrayList<>();
                            JSONArray array = new JSONObject(ret).getJSONArray("result");
                            String defaultVal = getString(R.string.default_country);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                Region region = new Gson().fromJson(object.toString(), Region.class);
                                regionRet.regionArrayList.add(region);
                                if (region.regionName.equals(defaultVal) || region.regionCode.equals("86")) {
                                    currentRegion = region;
                                }
                            }
                            mRegionRet = regionRet;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("Get Region", "Error : " + errorMsg);
            }
        }).request();
    }

    @OnClick(R2.id.loginTxt)
    public void toLogin() {
        finish();
    }

    private boolean passwordIsShow;
    private boolean passwordCheckIsShow;

    @OnClick({R2.id.iv_password_hide_or_show, R2.id.iv_password_check_hide_or_show, R2.id.tv_privacy_policy})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_password_hide_or_show) {
            if (passwordIsShow) {
                passwordIsShow = false;
                ivPasswordHideOrShow.setImageResource(R.mipmap.password_hide);
                password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                password.setSelection(password.getText().toString().length());
            } else {
                passwordIsShow = true;
                ivPasswordHideOrShow.setImageResource(R.mipmap.password_show);
                password.setInputType(InputType.TYPE_CLASS_TEXT);
                password.setSelection(password.getText().toString().length());
            }
        } else if (id == R.id.iv_password_check_hide_or_show) {
            if (passwordCheckIsShow) {
                passwordCheckIsShow = false;
                ivPasswordCheckHideOrShow.setImageResource(R.mipmap.password_hide);
                repeatPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                repeatPassword.setSelection(repeatPassword.getText().toString().length());
            } else {
                passwordCheckIsShow = true;
                ivPasswordCheckHideOrShow.setImageResource(R.mipmap.password_show);
                repeatPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                repeatPassword.setSelection(repeatPassword.getText().toString().length());
            }
        } else if (id == R.id.tv_privacy_policy) {
            Intent intent = new Intent(this, UserAgrementActiviy.class);
            startActivity(intent);
        }
    }

}
